package com.xhl.doeverything.rabbitmq.service;

import com.alibaba.fastjson.JSON;
import com.xhl.doeverything.entity.SysEvent;
import com.xhl.doeverything.rabbitmq.constant.SysEventExchangeName;
import com.xhl.doeverything.rabbitmq.constant.SysEventRoutingKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author xionghuilong
 * @description: rabbitmq发送端
 * @date 2022/1/17 11:18
 */
@Service
public class MessageSender {
    private static final Logger log = LoggerFactory.getLogger(MessageSender.class);
    @Autowired
    private RabbitTemplate rabbitTemplate;

    public MessageSender() {
    }

    public <T> void send(SysEventExchangeName exchange, SysEventRoutingKey routingKey, SysEvent<T> event) {
        event.setSendTime(new Date());
        String msg = JSON.toJSONString(event);
        this.send(exchange, routingKey, msg);
    }

    public <T> void send(SysEventExchangeName exchange, SysEventRoutingKey routingKey, String plainText) {
        try {
            this.rabbitTemplate.convertAndSend(exchange.getCode(), routingKey.getRoutingKey(), plainText);
            if (log.isDebugEnabled()) {
                log.debug("{} 根据路由规则 {} 成功发送消息，body：{}", new Object[]{exchange, routingKey, plainText});
            }
        } catch (Exception var5) {
            log.error("{} 根据路由规则 {} 发送消息失败，body：{}", new Object[]{exchange, routingKey, plainText, var5});
        }

    }
}
